/**
 * promise 形式  getSetting
 */
export const getSetting = () => {
	return new Promise((resolve, reject) => {
		uni.getSetting({
			success: (result) => {
				resolve(result);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}
/**
 * promise 形式  chooseAddress
 */
export const chooseAddress = () => {
	return new Promise((resolve, reject) => {
		uni.chooseAddress({
			success: (result) => {
				resolve(result);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

/**
 * promise 形式  openSetting
 */
export const openSetting = () => {
	return new Promise((resolve, reject) => {
		uni.openSetting({
			success: (result) => {
				resolve(result);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}
/**
 *  promise 形式  showModal
 * @param {object} param0 参数
 * @param showCancel 是否显示取消按钮默认为 true
 * @param content 提示的内容
 */
export const showModal = ({
	content
}) => {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '提示',
			content: content,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}


/**
 *  promise 形式  showToast
 * @param {object} param0 参数
 */
export const showToast = ({
	title
}) => {
	return new Promise((resolve, reject) => {
		uni.showToast({
			title: title,
			icon: 'none',
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}

/**
 * promise 形式  login
 */
export const login = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			timeout: 10000,
			success: (result) => {
				resolve(result);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}
/**
 * promise 形式  getClipboardData
 */
export const getClipboardData = (title) => {
	return new Promise((resolve, reject) => {
		uni.getClipboardData({
			success: (res) => {
				if (res.data == '') {
					showToast(title)
				}
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

/**
 * promise 形式  setClipboardData
 */
export const setClipboardData = ({
	data
}) => {
	return new Promise((resolve, reject) => {
		uni.setClipboardData({
			data: data,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

/**
 * promise 形式  downloadFile
 */
export const downloadFile = ({
	url
}) => {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url: url,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

/**
 * promise 形式  saveVideoToPhotosAlbum
 */
export const saveVideoToPhotosAlbum = ({
	filePath
}) => {
	return new Promise((resolve, reject) => {
		uni.saveVideoToPhotosAlbum({
			filePath: filePath,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

/**
 * promise 形式  chooseMedia
 */
export const chooseMedia = () => {
	return new Promise((resolve, reject) => {
		uni.chooseMedia({
			count: 1,
			mediaType: ['video'],
			sourceType: ['album'],
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}


/**
 * promise 形式  从本地相册选择图片或使用相机拍照。
 */
export const chooseImage = ({
	count
}) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: count,
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			success: (result) => {
				resolve(result);
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

/**
 * promise 形式的 小程序的微信支付
 * @param {object} pay 支付所必要的参数
 */
export const requestPayment = (pay) => {
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			...pay,
			success: (result) => {
				resolve(result)
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}

/**
 * promise 形式的 获取定位
 */
export const getLocation = () => {
	return new Promise((resolve, reject) => {
		uni.getLocation({
			type: 'wgs84',
			success: function(res) {
				resolve(res)
			},
			fail: (err) => {
				reject(err);
			}
		});
	})
}



export const tranNumber = (value) => {
	let numerical = [];
	let k = 10000,
		sizes = ['', '万', '亿', '万亿'],
		i;
	if (value < k) {
		numerical = Number(value).toFixed(0)
	} else {
		i = Math.floor(Math.log(value) / Math.log(k));
		numerical = ((value / Math.pow(k, i))).toFixed(0) + sizes[i];
	}
	return numerical;
}
/**将数字转换成金融数据 */
export const thousands = (num) => {
	let str = num.toString()
	let reg = str.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g
	return str.replace(reg, "$1,")
}

/**
 * 时间戳转换成最近时间
 */
export const rexTime = (timestamp) => {
	if (!timestamp) return timestamp;
	let stamp = new Date(timestamp);
	let diffTime = Math.floor((Date.now() - stamp.getTime()) / 1000); //相差时间
	if (diffTime < 3600) {
		if (diffTime < 0) {
			return '1秒前'
		}
		if (diffTime < 60) {
			return diffTime + '秒前';
		}
		return Math.floor(diffTime / 60) + '分钟前';
	} else {
		const nowFirst = new Date().setHours(0, 0, 0, 0); //当天零点的时间戳
		const beforeWeek = new Date().setDate(new Date().getDate() - 7); //一周前的时间
		const yesterday = new Date(nowFirst - 86400000).getTime(); //昨天
		const stampNums = stamp.getTime(); //给定时间 戳
		const stampHours = stamp.getHours() < 10 ? '0' + stamp.getHours() : stamp.getHours(); //给定时间 时
		const stampMinutes = stamp.getMinutes() < 10 ? '0' + stamp.getMinutes() : stamp.getMinutes(); //给定时间 分
		if (stampNums > nowFirst) {
			return `${stampHours}:${stampMinutes}`;
		} else if (stampNums < nowFirst && yesterday <= stampNums) {
			return `昨天${stampHours}:${stampMinutes}`;
		} else if (beforeWeek < stampNums) {
			const weekData = ['日', '一', '二', '三', '四', '五', '六'];
			const stampWeeks = stamp.getDay(); //给定时间 星期
			return `星期${weekData[stampWeeks]} ${stampHours}:${stampMinutes}`;
		} else {
			const stampYears = stamp.getFullYear(); //给定时间 年
			const stampMonths = stamp.getMonth() + 1 < 10 ? ' ' + stamp.getMonth() + 1 : stamp.getMonth() +
				1; //给定时间 月
			const stampDates = stamp.getDate() < 10 ? '0' + stamp.getDate() : stamp.getDate(); //给定时间 日
			const nowYears = new Date().getFullYear();
			return `${stampYears === nowYears ? '' : stampYears.toString().substring(2, 4) + '年'}${stampMonths}月${stampDates}日`;
		}
	}
}


/**保留小数点后的数字
 n:要处理的数据，
 fixed:要保留的位数
 */
export const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);

/**
 *  获取所有参数平均值
 * @param {Array} args 参数
 */
export const average = (...args) => args.reduce((a, b) => a + b) / args.length;

/**
 *  大于99的数字变成99+
 * @param value 参数
 */
export const numLimit = (value) => {
	return value > 99 ? '99+' : value
}
/**手机号中间四位隐藏 */
export const handlePhone = (val) => val.substr(0, 3) + '****' + val.substr(7);

/**获取链接中包含的参数 */
export const getParams = (url) => {
	const paramObj = {}
	const params = url.split('?')[1]
	if (!params) return paramObj
	const keyValueArr = params.split('&')
	keyValueArr.forEach(item => {
		const keyValue = item.split('=')
		paramObj[keyValue[0]] = decodeURIComponent(keyValue[1])
	})

	return paramObj
}

export const splitAddress = (address) => {
	// 省市区正则表达式
	const regex =
		/^(?<province>[^省]+省|.+自治区|[^澳门]+澳门|[^香港]+香港|[^市]+市)?(?<city>[^自治州]+自治州|[^特别行政区]+特别行政区|[^市]+市|.*?地区|.*?行政单位|.+盟|市辖区|[^县]+县)(?<county>[^县]+县|[^市]+市|[^镇]+镇|[^区]+区|[^乡]+乡|.+场|.+旗|.+海域|.+岛)?(?<address>.*)$/;

	// 匹配地址字符串
	const match = regex.exec(address);
	console.log(match);
	// 返回拆分结果
	return {
		province: match.groups.province || match.groups.city,
		city: match.groups.city,
		district: match.groups.county,
		detail: match.groups.address,
	}
}

export const randomString = (len) => {
	len = len || 32;
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	var maxPos = $chars.length;
	var pwd = '';
	for (let i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}

/**
 * 日期格式化
 */
export const dateFormat = (date, format) => {
	format = format || 'yyyy-MM-dd hh:mm:ss';
	if (date !== 'Invalid Date') {
		let o = {
			"M+": date.getMonth() + 1, //month
			"d+": date.getDate(), //day
			"h+": date.getHours(), //hour
			"m+": date.getMinutes(), //minute
			"s+": date.getSeconds(), //second
			"q+": Math.floor((date.getMonth() + 3) / 3), //quarter
			"S": date.getMilliseconds() //millisecond
		}
		if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
			(date.getFullYear() + "").substr(4 - RegExp.$1.length));
		for (let k in o)
			if (new RegExp("(" + k + ")").test(format))
				format = format.replace(RegExp.$1,
					RegExp.$1.length === 1 ? o[k] :
					("00" + o[k]).substr(("" + o[k]).length));
		return format;
	}
	return '';
}
export const isToday = (timeStr) => {
	// 将时间字符串转换为Date对象
	const inputDate = new Date(timeStr);

	// 获取当前日期
	const today = new Date();

	// 比较年、月、日是否相同
	return (
		inputDate.getFullYear() === today.getFullYear() &&
		inputDate.getMonth() === today.getMonth() &&
		inputDate.getDate() === today.getDate()
	);
}
//通过身份证号计算年龄、性别、出生日期
export const idCard = (userCard, num) => {
	//获取出生日期
	var birth;
	if (num == 1) {
		birth = userCard.substring(6, 10) + "-" + userCard.substring(10, 12) + "-" + userCard.substring(12, 14);
		return birth;
	}
	//获取性别
	if (num == 2) {
		if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
			return "男";
		} else {
			return "女";
		}
	}
	//获取年龄
	if (num == 3) {
		var myDate = new Date();
		var month = myDate.getMonth() + 1;
		var day = myDate.getDate();
		var age = myDate.getFullYear() - userCard.substring(6, 10) - 1;
		if (userCard.substring(10, 12) < month || userCard.substring(10, 12) == month && userCard.substring(12,
				14) <= day) {
			age++;
		}
		return age;
	}
}

export const getWeekday = (date) => {
	const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
	const dayIndex = date.getDay(); // 获取星期几，返回值为 0-6
	return daysOfWeek[dayIndex];
}

// 获取时间偏移时间
export const getOffsetTime = (time, offset) => {
	const date = new Date(time);
	date.setDate(date.getDate() + offset);
	return date;
}
// 获取当前时间
export const getCurrentTime = () => {
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const day = String(now.getDate()).padStart(2, '0');
	const hours = String(now.getHours()).padStart(2, '0');
	const minutes = String(now.getMinutes()).padStart(2, '0');
	const seconds = String(now.getSeconds()).padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 自定义时间 将  HH:mm 转换为 yyyy-MM-dd HH:mm:ss
export const formatHmTime = (time) => {
	const [hour, minute] = time.split(':');
	const now = new Date();
	const year = now.getFullYear();
	const month = String(now.getMonth() + 1).padStart(2, '0');
	const day = String(now.getDate()).padStart(2, '0');
	return `${year}-${month}-${day} ${hour}:${minute}:00`;
}
// 时间戳 转换为 yyyy-MM-dd HH:mm:ss
export const formatTime = (time) => {
	const date = new Date(time);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	const seconds = String(date.getSeconds()).padStart(2, '0');
	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// yyyy-MM-dd HH:mm:ss 转换为时间戳
export const parseTime = (time) => {
	const [date, timePart] = time.split(' ');
	const [year, month, day] = date.split('-');
	const [hours, minutes, seconds] = timePart.split(':');
	return new Date(year, month - 1, day, hours, minutes, seconds).getTime();
}

// yyyy-MM-dd HH:mm:ss 转换为 HH:mm
export const formatHm = (time) => {
	const date = new Date(time);
	// 格式化为 HH:mm（自动补零）
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	// 短路运算处理无效值
	return hours?.length === 2 && minutes?.length === 2
		? `${hours}:${minutes}`
		: "--:--";
}